<template>
	<view>
		<showNewData ref='chrilds' ></showNewData>
		<view class="top_bar" style="background: rgba(244,244,244,0.96);border-bottom:1rpx solid #b5b5b5;" >
			<view @click="backLogin" class="top_bar_left" >
				<image src="../../static/fh.png" mode=""></image>
			</view>
			<view class="top_bar_center">
				<text>{{ viewtitle }}</text>
			</view>
			<view class="top_bar_right bar_chage" >
				<image  @click="toGroup" v-if='pagetype==1' :src='groupdata.group_img' mode="" ></image>
			</view>
		</view>
		
		<!-- 滚动动画 scroll-with-animation="true"  -->
		<scroll-view scroll-y="true" class="chat" :scroll-with-animation='scroll_animation' :scroll-into-view="scrollToView" @scrolltoupper='loading' >
			<view class="chat-main" :style="{paddingBottom:inputh + 'px'}" >
				<view class="loading" :class="{displaynone:loadingshow}" >
					<image :animation="animationData"  id='loading' src="../../static/loading.png" mode=""></image>
				</view>
				<view class="char-ls"
				v-for="item,index in message" :key='index' :id='"msg"+item.id'
				>
					<view v-show="item.time != '刚刚'" class="chart-time">{{ item.time }}</view>
					<view class="msg-m msg-left" v-if='item.tip==0' >
						<image @click="toUserMain(item.uid)"  :src="item.userimg" mode=""></image>
						<!-- 文字 -->
						<view class="message" v-if="item.types==0" >
							<view class="message-text">
								{{ item.message }}
							</view>
						</view>
						<!-- 图片 -->
						<view class="message" v-if="item.types==1" >
							<view class="message-img">
								<image @click="viewImg(item.message)" id="message-img" :src="item.message" mode="widthFix"></image>
							</view>
						</view>
						<!-- 音频 -->
						<view class="message" v-if="item.types==2" >
							<view class="message-text message-vioce" @tap="playVioce(item.message.vioce)" :style="{width:item.message.time*4+'px'}" >
								<image src="../../static/lb.png" id="vioce-img-left" mode=""></image>
								<text>{{ item.message.time }}°</text>
							</view>
						</view>
						<!-- 位置 -->
						<view class="message"  >
							<view class="message-map" v-if="item.types==3"  >
								<view class="map-name">{{ testdata.name }}</view>
								<view class="map-address">{{ testdata.address }}</view>
								<map class='map' :latitude="testdata.latitude" :longitude="testdata.longitude" :markers='markers(item.message)'></map>
							</view>
						</view>
					</view>
					<view class="msg-m msg-right" v-if='item.tip==1' >
						<image  :src="item.userimg"  mode=""></image>
						<view class="message" v-if="item.types==0"  >
							<view class="message-text">
								{{ item.message }}
							</view>
						</view>
						<view class="message" v-if="item.types==1" >
							<view class="message-img">
								<image @click="viewImg(item.message)" id='message-img' :src="item.message" mode="widthFix"></image>
							</view>
						</view>
						<view class="message" v-if="item.types==2" >
							<view class="message-text message-vioce" @tap="playVioce(item.message.vioce)"  :style="{width:60+item.message.time*4+'px'}">
								<text>{{ item.message.time }}°</text>
								<image src="../../static/lb.png" id="vioce-img-right" mode=""></image>
							</view>
						</view>
						<view class="message" v-if="item.types==3" >
							<view class="message-map">
								<view class="map-name">{{ testdata.message.name }}</view>
								<view class="map-address">{{ testdata.message.address }}</view>
								<map class='map' :latitude="testdata.message.latitude" :longitude="item.message.longitude" :markers='markers(item.message)'></map>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="pabdt"></view> -->
		</scroll-view>
		<submit :groupId="groupdata.groupid" :frendid='frendid' :userinfo="userinfo" @inputs='inputs' @heights='heights' ></submit>
	</view>
</template>

<script>
	import showNewData from '../../components/showNewData.vue'
	import datas from '../../commons/js/data.js'
	import dateformat from '../../commons/js/dateformat.js'
	import submit from '../../components/submit.vue'
	import request from '../../utails/request.js'
	const innerAudioContext = uni.createInnerAudioContext();
	
	export default {
		data() {
			return {
				viewtitle:'',// 页面标题 
				pagetype:0,// 0 私聊  1 群聊
				frendid:'',
				userinfo:{},
				groupdata:{}, // 若是群聊 => 群聊信息
				message:[],
				imgMsg:[] ,// 预览图片信息
				scrollToView:'', // 页面滚动
				inputh:'60' ,// 底部距离
				maxId:0, // 加载页面的的最后数据
				maxPageId:0, //整个页面的最大id
				animationData:{},
				scroll_animation:true,// 滚动动画
				loadingtime:'',// 加载数据的定时器
				loadingshow:true,// 加载效果展示
				nowpage:1,// 现在的页码
				maxpage:0, // 最大页码
				
				// 临时数据
				testdata:datas.maps()
			}
		},
		components:{
			submit,
			showNewData
		},
		onLoad(e) {
			// console.log(this)
			// 好友id
			// console.log(e)
			this.frendid = parseInt(e.id)
			if(e.group){
				this.pagetype=1
			}
			// 校验用户
			// 获取用户信息
			this.userinfo = uni.getStorageSync('userinfo')
			
			// let msg = datas.chatroon()
			// 连接ws
			this.onSocket()
			this.$nextTick(function(){
				this.getSocketData()
			})
			
			
			this.getMessage(this.frendid)
			// 获取最大id
			setTimeout(()=>{
				this.maxPageId = this.message[this.message.length-1].id
			},1000)
		},
		// 页面关闭 
		onUnload(){
			this.clearUnRead()
		},
		methods: {
			
			// 接收输入框信息 -- 点击发送 - 在后面补充数据
			async inputs(e){
				let data = {
					id : this.maxPageId + 1,
					userimg:this.userinfo.userimg,
					message:e.message,
					types:e.types,
					time: dateformat.format1(new Date()),
					tip:1,
					username:this.userinfo.username // 提供给首页
					}
				console.log(data.message)
				// 预览图片处理
				if(e.types==1){
					this.imgMsg.push(eval(e.message))
					data.message = eval(data.message)
				}
				// 地图信息
				if(e.types==3){
					data.message = String(data.message) // 转化为string
					console.log(data.messagse)
				}
				
					
				// 页面渲染
				this.message.push(data)
				this.maxPageId += 1
				this.goBottom(this.maxPageId)
				
				// socket
				this.sendSocket(data)
				this.sedShow(data)
				
				// 发送给后端 文本
				if(e.types==0||e.types==2){
					data['usera']=this.userinfo.id
					data['userb']=this.frendid
					let resp = {}
					if(this.pagetype==1){
						resp = await request.request2({url:'/groupview/',data,method:'POST'})
					}else{
						resp = await request.request2({url:'/chatroom/',data,method:'POST'})
					}
					console.log(resp)	
				}
			},
			// Socket.io
			// 发送socket 提醒
			sedShow(data){
				this.socket.emit('show',data,this.frendid)
			},
			// 接socket提醒
			getSocketData(){
				this.socket.emit('login',this.userinfo.id)
				this.socket.on('shows',(data)=>{
					let datas = {
						userimg:data.userimg,
						username:data.username,
						message:data.message
					}
					// ref 不可重复
					// this.$refs.chrilds.handleShow()
					this.$emit('shownewdata',datas)
				})
			},
			
			// 发送socket
			sendSocket(data){
				if(this.pagetype==0){
					// 一对一聊天  // 自己  他人
					console.log('send')
					this.socket.emit('msg',data,this.userinfo.id,this.frendid)
				}else{
					// 群消息
					this.socket.emit('groupMsg',data,this.userinfo.id,this.groupdata.groupid)
				}
			},
			// 接收socket消息
			onSocket(){
				let url = ''
				if(this.pagetype==1){
					url = `groupMsgs`
				}else{
					url = 'msgs'
				}
				this.socket.on(url,(msg,fid)=>{
					console.log(msg + '是' + fid + '发的')
					// if(this.frendid==fid){
						let data = {
							id : msg.id,
							userimg:msg.userimg,
							message:msg.message,
							types:msg.types,
							time: dateformat.format1(new Date()),
							tip:0
							}
						// 预览图片处理
						if(data.types==1){
							this.imgMsg.push(msg.message)
										
						}
						// 页面渲染
						this.message.push(data)
						this.maxPageId += 1
						this.goBottom(this.maxPageId)
					// }
				})
			},
			
			// 点击表情，高度改变
			heights(e){
				console.log(e)
				this.inputh = e
				this.goBottom(this.maxPageId)
			},
			// 滚动到底部
			goBottom(max){
				this.scrollToView = ''
				console.log(max)
				this.$nextTick(function(){
					this.scrollToView = 'msg' + max
				})
			},
			
			// 获取信息 - 获取旧数据
			async getMessage(id){
				
				let data = {
					usera:this.userinfo.id,
					userb:id,
					nowpage:this.nowpage,
					maxpage:this.maxpage
				}
				let resp = []
				if(this.pagetype==1){
					resp = await request.request2({url:'/groupview/', data})
				}else{
					resp = await request.request2({url:'/chatroom/', data})
				}
				this.maxpage = resp.maxpage
				
				let buttomView = 0 // 加载10条数据中最大的
				if(resp.data){
					resp.data.forEach(v=>{
						v.time = dateformat.format3(v.time)
						if(v.types==1){
							this.imgMsg.unshift(v.message)
						}
						else if(v.types==3){
							v.message = eval(v.message)
						}
						v.id>=buttomView? buttomView=v.id:buttomView
					})
				}
				// 新获取数据（旧数据-上）  原本数据 （新数据-下）
				this.message = [...resp.data,...this.message]
				// 加载群聊信息
				if(this.pagetype==1){
					this.groupdata = resp.group
					this.viewtitle = this.groupdata.groupname
				}else{
					this.viewtitle = resp.friend.fname
				}
				// 取消加载动画
				clearInterval(this.loadingtime)
				this.loadingshow = true
				// 显示在最下端
				this.maxId = buttomView
				this.goBottom(this.maxId)
				setTimeout(()=>{
					this.scroll_animation = true // 恢复滚动
				},500)
			},
			// 预览图片
			viewImg(e){
				let index = 0
				this.imgMsg.forEach((v,i)=>{
					if(v == e){
						index = i
					}
				})
				uni.previewImage({
					current:index,
					urls: this.imgMsg,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});

			},
			// 音频播放
			playVioce(e){
				innerAudioContext.autoplay = true;
				innerAudioContext.src = e
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
			},
			
			// 地图标记
			markers(e){
				let map = [{
					latitude: e.latitude,
					longitude: e.longitude,
					iconPath: '../../static/dw.png'
				}]
				return (map)
			},
			
			// 滑动顶部加载下一页
			  loading(){
				// 当最后一页时
				if(this.nowpage==this.maxpage){
					uni.showToast({
						title:'没有更多了',
						icon:'none',
						duration:2000
					})
					return
				}
				
				// 页面加一
				this.nowpage++
			    var animation = uni.createAnimation({
			      duration: 1000,
			        timingFunction: 'ease',
			    })
				this.loadingshow=false // 加载效果展示
			    this.animation = animation
				let i = 0
			    this.loadingtime =  setInterval(function() {
			      animation.rotate(i*60).step()
			      this.animationData = animation.export()
				  i++
			    }.bind(this), 200)
				this.scroll_animation = false // 取消滚动动画
				// 获取数据 request
				this.getMessage(this.frendid)
			
			  },
			// 进入群聊  
			toGroup(){
				uni.navigateTo({
					url:'../grouphome/grouphome?groupname='+ this.groupdata.groupname
				})	
			},
			
			// 跳转到用户主页
			toUserMain(uid){
				uni.navigateTo({
					url:'../user/user?id='+uid
				})
			},
			
			// 关闭页面 清空未读
			async clearUnRead(){
				let data = {
					usera:this.userinfo.id,
					userb:this.frendid
				}
				let res = {}
				if(this.pagetype==1){
					res = await request.request2({url:'/groupview/',data, method:'DELETE'})
				}else{
					res = await request.request2({url:'/chatroom/',data, method:'DELETE'})
				}
			},
			
			// 返回上一页
			backLogin(){
				uni.navigateBack({
					delta:1
				})
			}
		}
	}
</script>

<style>
	@import '../../commons/css/myss.scss';
	
	.content{
		height: 100%;
	}
	
	.bar_chage{
		padding: 4rpx;
		height: 80rpx;
		width: 80rpx;
		padding-right: 20rpx;
		border-radius: 32rpx;
	}
	
	.chat{
		height: 100vh;
		background-color: #eeeeee;
	}
	.chat .chat-main{
		padding-left: 32rpx;
		padding-right: 32rpx;
		padding-top: 100rpx;
		/* padding-bottom: 120rpx; */
		display: flex;
		flex-direction: column;
	}
	
	 /* 内容 */
	.chat .chat-main .char-ls{
		
	}
	.chat .chat-main .char-ls .chart-time{
		padding: 20rpx 0;
		font-size: 24rpx;
		color: #BABAB5;
		text-align: center;
	}
	.chat .chat-main .char-ls .msg-m{
		display: flex;
		padding: 20rpx 0;
		
	}
	.chat .chat-main .char-ls .msg-m image{
		flex: none;
		width: 88rpx;
		height: 80rpx;
		border-radius: 32rpx;
	}
	.message{
		flex: auto;
		max-width: 400rpx;
	}
	.message-text{
		padding: 18rpx 24rpx;
		font-size: 30rpx;
		line-height: 44rpx;
		color: #555555;
	}
	
	 #message-img{
		width: 320rpx;
		max-width: 400rpx;
	}
	
	/* 左边 */
	.msg-left{
		flex-direction: row;
	}
	.msg-left .message .message-text{
		float: left;
		margin-left: 15rpx;
		background-color: #fff;
		border-radius: 5px 20px 20px 20px;
	}
	
	/* 右边 */
	.msg-right{
		flex-direction: row-reverse;
	}
	.msg-right .message .message-text{
		float: right;
		margin-right: 15rpx;
		background-color: #f4ea2a;
		border-radius: 20px 5px 20px 20px;
	}
	.msg-right .message .message-img #message-img{
		float: right;
	}
	
	 /* 隔开 */
	.pabdt{
		height: var(--status-bar-height);
		width: 100%;
	}
	
	/* 音频 */
	.message-vioce{
		max-width: 400rpx;
		min-width: 60rpx;
		height: 44rpx;
	}
	
	.message-vioce text{
		padding: 0 20rpx;
		font-size: 34rpx;
		text-align: left;
	}
	..message-vioce-r text{
		padding: 0 20rpx;
		font-size: 34rpx;
		text-align: right;
	}
	
	#vioce-img-left{
		margin: 0;
		width: 36rpx;
		height: 36rpx;
	}
	#vioce-img-right{
		margin: 0;
		width: 36rpx;
		height: 36rpx;
		transform: rotate(180deg);
	}
	
	/* 位置 */
	.message .message-map{
		background-color: #fff;
		width: 400rpx;
		/* border-radius: 20rpx 0rpx 20rpx 20rpx; */
	}
	.message .message-map .map-name{
		font-size: 32rpx;
		line-height: 40rpx;
		color: #444444;
		padding: 18rpx 14rpx 0rpx 14rpx;
		display: -webkit-box;
		overflow: hidden; 
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		/* border-radius: 15rpx rpx 15rpx 15rpx; */
	}
	.message .message-map .map-address{
		font-size: 20rpx;
		color: #737373;
		padding: 0rpx 14rpx;
		display: -webkit-box;
		overflow: hidden; 
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
	}
	.message .message-map .map{
		width: 400rpx;
		height: 190rpx;
		/* border: 0rpx 0rpx 20rpx 20rpx; */
	}
	
	/*  */
	.loading{
		text-align: center;
	}
	
	#loading{
		width: 60rpx;
		height: 60rpx;
	}
	
	.displaynone{
		display: none;
	}
</style>
